package com.ivanceras.server.services;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ivanceras.server.util.CStringUtils;
import com.ivanceras.server.util.Configuration;
import com.ivanceras.shared.db.EMF;
import com.ivanceras.shared.db.EntityManager;
import com.ivanceras.shared.exception.DatabaseException;

/**
 * Fetch all tables in this server
 * @author lee
 *
 */
public class XmlTableServlet extends HttpServlet {


	/**
	 * 
	 */
	private static final long serialVersionUID = -5359445752623415808L;
	public void doGet(HttpServletRequest req, HttpServletResponse res)
	throws ServletException, IOException {

		res.setContentType("text/xml");
		PrintWriter out = res.getWriter();
		String schema = req.getParameter("schema");
		String specificTables = req.getParameter("tables");
		schema = schema == null ? Configuration.dbSchema : schema;
		EntityManager em = null;
		HashMap<String, Integer> tableCountList = new HashMap<String, Integer>();
		try {
			em = EMF.get();
			String[] tableList  = null;
			if(specificTables != null){
				tableList = specificTables.split("\\,");
			}else{
				String tablePattern = req.getParameter("pattern");
				tablePattern = tablePattern == null ? "%" : tablePattern;
				tableList = em.getDB().getTableNames(schema, tablePattern);
			}
			for(String table : tableList){
				int totalCount = em.getTotalRecords("DAO_"+CStringUtils.capitalize(table.toLowerCase()));
				tableCountList.put(table, totalCount);
			}
		} catch (DatabaseException e1) {
			e1.printStackTrace();
		}
		finally{
			em.close();
		}
		printXml(out, tableCountList);
	}
	private void printXml(PrintWriter out, HashMap<String, Integer> tableCountList) {
		TreeMap<String, Integer> treemap = new TreeMap<String, Integer>();
		treemap.putAll(tableCountList);
		out.print("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
		out.print("\n<tables total=\""+tableCountList.size()+"\">");
		for(Entry<String, Integer> entry : treemap.entrySet()){
			String table = entry.getKey();
			Integer count = entry.getValue();
			System.out.println(table);
			out.append("\n\t\t<model name =\""+table+"\" count=\""+count+"\"/>");
		}
		out.print("\n</tables>");
	}
}